package com.starbaba.outsideapi.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.starbaba.core.web.page.PageRequest;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.outsideapi.model.OutSideApiEntity;
import com.starbaba.outsideapi.service.OutSideApiService;
import com.tuanzi.server.loan_base.util.PhoneNumNideUtil;

@SuppressWarnings("deprecation")
public class OutSideApiServiceImpl implements OutSideApiService {
	static BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	@Override
	public void showpage(Map<String, Object> paramsMap) {
		String sql = "select id as activity_id, name as activity_name  from loan_content_activity";
		try {
			List<OutSideApiEntity> list = dao.list(sql, OutSideApiEntity.class);
			paramsMap.put("activityList", list);
		} catch (AppException e) {
			LogService.error(e);
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<OutSideApiEntity> showApiList(Map<String, Object> paramsMap, PageRequest pageRequest,
			PageResponse pageResponse) {
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		List<OutSideApiEntity> list = new ArrayList<OutSideApiEntity>();
		StringBuffer sqlList = new StringBuffer();
		sqlList.append("SELECT a.id AS orderid,a.source_id AS activity_id,a.mobnum as phone,a.status,a.result_type,a.petname AS name,a.idcard,a.ctime AS checktime,");
		sqlList.append(" b.activetime AS registertime ");
		sqlList.append("FROM loan_external_api_record a LEFT JOIN comm_user b ON a.userid=b.id ");
		sqlList.append(" WHERE 1=1 ");
		fillQueryConditionByUser(paramsMap, sqlList);
		sqlList.append(" ORDER BY a.ctime DESC");
		
		try {
			int count = dao.getInt("select count(z.orderid) from (" + sqlList.toString() + ") z");
			if (sqlList.length() > 0 && start >= 0 && length > 0) {
				sqlList.append(" LIMIT " + start + ", " + length);
			}
			list = dao.list(sqlList.toString(), OutSideApiEntity.class);
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		} catch (AppException e) {
			LogService.error(e);
		}
		List<OutSideApiEntity> data = new ArrayList<OutSideApiEntity>();
		for (OutSideApiEntity dataList : list) {
			
			if("0".equals(dataList.getStatus())){
				dataList.setStatus("0");	//验证失败		
			}
			if(!StringUtils.isEmpty(dataList.getRegistertime())&&"1".equals(dataList.getStatus())){
				dataList.setStatus("2"); //菠萝贷注册
			}
			if (StringUtils.isEmpty(dataList.getRegistertime())&&"1".equals(dataList.getStatus())) {
				dataList.setStatus("1"); //验证成功
			}
			
			dataList.setPhone(PhoneNumNideUtil.hideNum(dataList.getPhone()));
			dataList.setName(PhoneNumNideUtil.hideName(dataList.getName()));
			data.add(dataList);
		}
		return data;
	}
	
	
	@SuppressWarnings("rawtypes")
	@Override
	public List<OutSideApiEntity> showCollaborateList(Map<String, Object> paramsMap, PageRequest pageRequest,
			PageResponse pageResponse) {
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		List<OutSideApiEntity> list=new ArrayList<OutSideApiEntity>();
		StringBuffer sql=new StringBuffer();
		sql.append("SELECT a.activity_id,a.mannum,b.tnum ,c.rnum,a.channel_id,a.checktime from ");
		sql.append("(SELECT source_id AS activity_id,channel_id,COUNT(id) as mannum,api_type,DATE_FORMAT(ctime,'%Y-%m-%d') AS checktime FROM loan_external_api_record GROUP BY checktime) a LEFT JOIN ");
		sql.append("(SELECT a.source_id AS activity_id, COUNT(a.source_id) as tnum,DATE_FORMAT(a.ctime,'%Y-%m-%d') AS checktime,b.activedate as registertime FROM loan_external_api_record a LEFT JOIN comm_user b ON a.userid = b.id WHERE a.`STATUS`=1 AND 	b.activetime is null  GROUP BY checktime) b ON a.activity_id=b.activity_id and a.checktime=b.checktime LEFT JOIN ");
		sql.append("(SELECT a.source_id AS activity_id,COUNT(a.source_id) as rnum,DATE_FORMAT(a.ctime,'%Y-%m-%d') AS checktime FROM loan_external_api_record a LEFT JOIN comm_user b ON a.userid = b.id WHERE a.`STATUS`=1 AND 	b.activetime is not null  GROUP BY checktime) c ON a.activity_id=c.activity_id and a.checktime=c.checktime ");
		sql.append("WHERE 1=1 ");
		fillQueryConditionByCollaborate(paramsMap, sql);
		sql.append(" ORDER BY a.checktime DESC");
		try {
			int count = dao.getInt("select count(1) from ("+sql.toString()+") z");
			if (sql.length() > 0 && start >= 0 && length > 0) {
				sql.append(" LIMIT " + start + ", " + length);
			}
			list = dao.list(sql.toString(), OutSideApiEntity.class);
			pageResponse.setITotalDisplayRecords(count);
			pageResponse.setITotalRecords(count);
		} catch (AppException e) {
			LogService.error(e);
		}
		return list;
	}

	private void fillQueryConditionByUser(Map<String, Object> paramsMap, StringBuffer sqlList) {
		String apiType =  (String) paramsMap.get("api_type");
		String phone = (String) paramsMap.get("phone");
		String status = (String) paramsMap.get("status");
		String checkstartTime = (String) paramsMap.get("checkstartTime");
		String checkendTime = (String) paramsMap.get("checkendTime");
		String registerstartTime = (String) paramsMap.get("registerstartTime");
		String registerendTime = (String) paramsMap.get("registerendTime");
		String result_type = (String) paramsMap.get("result_type");
		
		if (!StringUtils.isEmpty(apiType)) {
			sqlList.append(" and a.api_type=" + apiType + "");
		}
		if (!StringUtils.isEmpty(phone)) {
			sqlList.append(" and a.mobnum='" + phone + "'");
		}
		if (!StringUtils.isEmpty(status)) {
			if ("2".equals(status)) { //菠萝贷注册
				sqlList.append(" and a.status=1 and b.activetime is not null ");
			} else if("1".equals(status)){//验证成功
				sqlList.append(" and a.status=1 and b.activetime is null ");
			}else{ //验证失败
				sqlList.append(" and a.status=0 ");
			}
		}
		if (!StringUtils.isEmpty(checkstartTime)) {
			sqlList.append(" and a.ctime>='" + checkstartTime + "'");
		}
		if (!StringUtils.isEmpty(checkendTime)) {
			sqlList.append(" and a.ctime<='" + checkendTime + "'");
		}
		if (!StringUtils.isEmpty(registerstartTime)) {
			sqlList.append(" and b.activetime>='" + registerstartTime + "'");
		}
		if (!StringUtils.isEmpty(registerendTime)) {
			sqlList.append(" and b.activetime<='" + registerendTime + "'");
		}
		if(!StringUtils.isEmpty(result_type)&&"1".equals(result_type)){
			sqlList.append(" and a.result_type='" + result_type + "'");
		}
	}

	private void fillQueryConditionByCollaborate(Map<String, Object> paramsMap, StringBuffer sql) {
		String apiType = (String) paramsMap.get("api_type");
		String checkstartTime = (String) paramsMap.get("checkstartTime");
		String checkendTime = (String) paramsMap.get("checkendTime");
		if (!StringUtils.isEmpty(apiType)) {
			sql.append(" and a.api_type='" + apiType + "'");
		}
		if (!StringUtils.isEmpty(checkstartTime)) {
			sql.append(" and a.checktime>='" + checkstartTime + "'");
		}
		if (!StringUtils.isEmpty(checkendTime)) {
			sql.append(" and a.checktime<='" + checkendTime + "'");
		}
	}

	@Override
	public String exportDetailCVS(List<OutSideApiEntity> list) {
		StringBuffer detail=new  StringBuffer();
		detail.append("订单编号,合作方,手机号,姓名,身份证,验证账号时间,菠萝带注册时间,状态\r\n");
		for (OutSideApiEntity outSideApiEntity : list) {
			detail.append(outSideApiEntity.getOrderid()).append(",");
			
			String activity_id = outSideApiEntity.getActivity_id();
			if("jiufudingdang".equals(activity_id)){		
				detail.append("玖富万卡").append(",");
			}else if("yikesiqi".equals(activity_id)){
				detail.append("亿科思齐").append(",");
			}else{
				detail.append("-").append(",");
			}
			
			detail.append(outSideApiEntity.getPhone()).append(",");
			detail.append(outSideApiEntity.getName()).append(",");
			detail.append(outSideApiEntity.getIdcard()).append(",");
			detail.append(outSideApiEntity.getChecktime()).append(",");
			detail.append(outSideApiEntity.getRegistertime()).append(",");
			
			String status = outSideApiEntity.getStatus();
			if("2".equals(status)){
				detail.append("菠萝贷注册").append(",");
			}else if("1".equals(status)){
				detail.append("验证成功").append(",");
			}else{
				detail.append("验证失败").append(",");
			}
			
			detail.append("\r\n");
		}
		return detail.toString();
	}

}
